package com.leyikao.util;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * http client 工具类
 * 
 * @author LoadChange
 *
 */
public class HttpTookit {
	private static final Logger logger = LoggerFactory.getLogger(HttpTookit.class);
	private static final CloseableHttpClient httpClient;
	public static final String CHARSET = "UTF-8";

	static {
		RequestConfig config = RequestConfig.custom().setConnectTimeout(60000).setSocketTimeout(15000).build();
		httpClient = HttpClientBuilder.create().setDefaultRequestConfig(config).build();
	}

	public static String doGet(String url, Map<String, String> params) {
		return doGet(url, params, CHARSET);
	}

	public static String doPost(String url, Map<String, String> params) {
		return doPost(url, params, CHARSET);
	}

	/**
	 * HTTP Get 获取内容
	 * 
	 * @param url
	 *            请求的url地址 ?之前的地址
	 * @param params
	 *            请求的参数
	 * @param charset
	 *            编码格式
	 * @return 页面内容
	 */
	public static String doGet(String url, Map<String, String> params, String charset) {
		if (StringUtils.isBlank(url)) {
			return null;
		}
		try {
			if (params != null && !params.isEmpty()) {
				List<NameValuePair> pairs = new ArrayList<NameValuePair>(params.size());
				for (Map.Entry<String, String> entry : params.entrySet()) {
					String value = entry.getValue();
					if (value != null) {
						pairs.add(new BasicNameValuePair(entry.getKey(), value));
					}
				}
				url += "?" + EntityUtils.toString(new UrlEncodedFormEntity(pairs, charset));
			}
			HttpGet httpGet = new HttpGet(url);
			CloseableHttpResponse response = httpClient.execute(httpGet);
			int statusCode = response.getStatusLine().getStatusCode();
			if (statusCode != 200) {
				httpGet.abort();
				throw new RuntimeException("HttpClient,error status code :" + statusCode);
			}
			HttpEntity entity = response.getEntity();
			String result = null;
			if (entity != null) {
				result = EntityUtils.toString(entity, "utf-8");
			}
			EntityUtils.consume(entity);
			response.close();
			return result;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * HTTP Post 获取内容
	 * 
	 * @param url
	 *            请求的url地址 ?之前的地址
	 * @param params
	 *            请求的参数
	 * @param charset
	 *            编码格式
	 * @return 页面内容
	 */
	public static String doPost(String url, Map<String, String> params, String charset) {
//		url = "http://4701c98a.nat123.net:47105/index.xhtml";
		url = "http://appserver.51manlicai.com/index.xhtml";
//		url = "http://192.168.40.157:8190/index.xhtml";
		if (StringUtils.isBlank(url)) {
			return null;
		}
		try {
			List<NameValuePair> pairs = null;
			if (params != null && !params.isEmpty()) {
				logger.info("请求网关url:"+url);
				logger.info("请求网关参数加密:"+params.toString());
				pairs = new ArrayList<NameValuePair>(params.size());
				for (Map.Entry<String, String> entry : params.entrySet()) {
					String value = entry.getValue();
					if (value != null) {
						pairs.add(new BasicNameValuePair(entry.getKey(), value));
					}
				}
			}
			HttpPost httpPost = new HttpPost(url);
			if (pairs != null && pairs.size() > 0) {
				httpPost.setEntity(new UrlEncodedFormEntity(pairs, CHARSET));
			}
			
			CloseableHttpResponse response = httpClient.execute(httpPost);
			int statusCode = response.getStatusLine().getStatusCode();
			if (statusCode != 200) {
				httpPost.abort();
				throw new RuntimeException("HttpClient,error status code :" + statusCode);
			}
			HttpEntity entity = response.getEntity();
			String result = null;
			if (entity != null) {
				result = EntityUtils.toString(entity, CHARSET);
			}
			EntityUtils.consume(entity);
			response.close();
			logger.info("接收网关应答-加密结果:"+result);
			return result;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public static void main(String[] args) {
		String url1 = "http://jingzhi.funds.hexun.com/270004.shtml";
		String result1 = doGet(url1, null,"utf8");
		Pattern p1 = Pattern.compile("<font  color=\"#ff0000\"><span>(.*)</span></font>");
        Matcher m1 = p1.matcher(result1);
        if (m1.find()) {
            String str1 =m1.group(1);//你的要的结果
            System.out.println(str1);
        }
        Pattern p2 = Pattern.compile("<font color=\"#ff0000\">(.*)</font>");
        Matcher m2 = p2.matcher(result1);
        if (m2.find()) {
            String str2 =m2.group(1);//你的要的结果
            System.out.println(str2);
        }
        
        String url2 = "http://fund.eastmoney.com/161010.html";
//        String url2 = "http://fund.eastmoney.com/161010.html";
		String result2 = doGet(url2, null,"utf8");
//		<li class="dwjz"><span class="ping">1.1770</span></li>
		Pattern pa1 = Pattern.compile("<li class=\"dwjz\"><span class=\"ping\">(.*)</span></li>");
      Matcher ma1 = pa1.matcher(result2);
      if (ma1.find()) {
          String strs1 =ma1.group(1);//你的要的结果
          System.out.println(strs1.subSequence(0, 6));
      }
      Pattern pa2 = Pattern.compile("<li class=\"ljjz\"><span class=\"ping\">(.*)</span></li>");
      Matcher ma2 = pa2.matcher(result2);
      if (ma2.find()) {
          String str2 =ma2.group(1);//你的要的结果
          System.out.println(str2.subSequence(0, 6));
      }
//		System.out.println(result2);
//		Pattern pa1 = Pattern.compile("<div id=\"statuspzgz\" class=\"fundpz\"><span class=\"red bold\">(.*)</span>");
//        Matcher ma1 = pa1.matcher(result2);
//        if (ma1.find()) {
//            String strs1 =ma1.group(1);//你的要的结果
//            System.out.println(strs1.subSequence(0, 6));
//        }
//        Pattern pa2 = Pattern.compile("<span class='right12'><span class=\"red bold\">(.*)</span></span>");
//        Matcher ma2 = pa2.matcher(result2);
//        if (ma2.find()) {
//            String str2 =ma2.group(1);//你的要的结果
//            System.out.println(str2.subSequence(0, 6));
//        }
        
        
	}
	
}